package chixing.day20.proxy.cglib_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLibProxy implements MethodInterceptor {
    private Object target;

    public CGLibProxy(Object target) {
        this.target = target;
    }

    //1.创建代理对象
    public Object newProxyInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        //target : 目标对象 父类  enhancer : 代理对象 子类
        enhancer.setCallback(this);
        return enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        //目标对象所有方法都要执行
        Object returnValue = method.invoke(target, args);

        if(method.getName().equals("add") || method.getName().equals("update")|| method.getName().equals("delete"))
            new LogUtil().addLog();
        return returnValue;
    }
}
